package cn.funeralobjects.ams.service.impl;

import cn.funeralobjects.ams.entity.EProduct;
import cn.funeralobjects.ams.model.Product;
import cn.funeralobjects.ams.repository.BaseAmsRepository;
import cn.funeralobjects.ams.repository.EProductRepository;
import cn.funeralobjects.ams.service.ProductService;
import cn.funeralobjects.common.service.annotataion.CommonService;
import cn.funeralobjects.common.service.exception.DataConflictException;
import cn.funeralobjects.common.service.validate.DataCheck;
import cn.funeralobjects.util.Assert;
import cn.funeralobjects.util.NumberUtils;
import cn.funeralobjects.util.annotation.ArgNotZero;
import cn.funeralobjects.util.annotation.AssertArg;

import javax.annotation.Resource;

/**
 * @author FuneralObjects
 * Create date: 2020/5/25 4:54 PM
 */
@CommonService
public class ProductServiceImpl implements ProductService, BaseJpaAmsService<Product, EProduct, Integer> {

    @Resource
    private EProductRepository eProductRepository;

    @Override
    public BaseAmsRepository<EProduct, Integer> baseAmsRepository() {
        return eProductRepository;
    }

    @AssertArg
    @Override
    public void checkConflict(@AssertArg Product product) throws DataConflictException {
        this.mustNotConflictByCode(product.getCode());
    }

    @Override
    public EProduct toEntity(Product product) {
        return product == null ? null : new EProduct()
                .setCode(product.getCode())
                .setDescription(product.getDescription());
    }

    @AssertArg
    @Override
    public void checkConflict(@AssertArg Product product, @ArgNotZero Integer withoutId) throws DataConflictException {
        DataCheck.conflictData(this.existsByCode(product.getCode()), () -> createDataCode("code", product.getCode()));
    }

    @Override
    public void copyToEntity(Product sourceModify, EProduct targetEntity) {
        targetEntity
                .setCode(sourceModify.getCode())
                .setDescription(sourceModify.getDescription());
    }

    @Override
    public boolean isValid(Integer id) {
        return NumberUtils.notZero(id);
    }

    @Override
    public void validateModify(Product product) {
        Assert.argAssert(product, "product");
    }
}
